package com.example.demo.utils;

import com.dampcake.bencode.Bencode;
import com.dampcake.bencode.Type;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.util.Map;
//now

public class TorrentUtil {

    private static final Bencode bencode = new Bencode(StandardCharsets.ISO_8859_1);

    public static byte[] injectTracker(File torrentFile, String trackerUrl) throws IOException {
        byte[] fileBytes = readBytes(torrentFile);

        Map<String, Object> torrentMap = bencode.decode(fileBytes, Type.DICTIONARY);

        // trackerUrl: ip:port + /announce / {passkey}
        torrentMap.put("announce", trackerUrl);

        return bencode.encode(torrentMap);
    }

    public static String getInfoHash(File torrentFile) throws IOException {
        byte[] fileBytes = readBytes(torrentFile);
        Map<String, Object> torrentMap = bencode.decode(fileBytes, Type.DICTIONARY);

        @SuppressWarnings("unchecked")
        Map<String, Object> info = (Map<String, Object>) torrentMap.get("info");

        // 对 info 字典重新编码
        byte[] infoBytes = bencode.encode(info);

        // 计算 SHA-1 hash
        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("SHA-1");
        } catch (Exception e) {
            throw new RuntimeException("SHA-1 not supported", e);
        }

        byte[] hash = sha1.digest(infoBytes);
        return bytesToHex(hash);
    }

    public static void saveToFile(byte[] data, File outputFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            fos.write(data);
        }
    }

    private static byte[] readBytes(File file) throws IOException {
        try (InputStream in = new FileInputStream(file)) {
            return in.readAllBytes();
        }
    }

    public static String bytesToHex(byte[] hash) {
        StringBuilder hex = new StringBuilder();
        for (byte b : hash) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }

    public static File multipartFileToFile(MultipartFile multipartFile) throws IOException {
        // 创建临时文件
        File file = File.createTempFile("torrent-", ".tmp");

        // 传输文件内容（使用try-with-resources确保流关闭）
        try (InputStream inputStream = multipartFile.getInputStream()) {
            Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        // 设置JVM退出时删除临时文件（可选）
        file.deleteOnExit();

        return file;
    }
}
